package com.sunwayworld.baseline.framework.utils;

import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.exception.InvalidDataException;
import com.sunwayworld.framework.mybatis.mapper.MapperParameter;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.module.sys.code.bean.CoreCodeBean;
import com.sunwayworld.module.sys.code.bean.CoreCodeCategoryBean;
import com.sunwayworld.module.sys.code.service.CoreCodeCategoryService;
import com.sunwayworld.module.sys.code.service.CoreCodeService;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TemplateExcelHelper {

    /**
     * 根据【选择内容】填充下拉框 （字段和下拉编码按顺序一一对应）
     *
     * @param sheet
     * @param rowIndex        标题行
     * @param columns         字段名称（模板批注）
     * @param codeCategoryIds 下拉编码（选择内容编码）
     */
    public static void fillSheetSelect(Sheet sheet, int rowIndex, String[] columns, String[] codeCategoryIds) {
        fillDropDown(sheet, rowIndex, gainSelectInfo(columns, codeCategoryIds));
    }

    /**
     * 从【选择内容】获取信息作为下拉框（字段和下拉编码按顺序一一对应）
     *
     * @param columns         字段名称（模板批注）
     * @param codeCategoryIds 下拉编码（选择内容编码）
     * @return
     */
    public static Map<String, List<String>> gainSelectInfo(String[] columns, String[] codeCategoryIds) {
        Map<String, List<String>> selectListMap = new HashMap<>();
        CoreCodeService coreCodeService = ApplicationContextHelper.getBean(CoreCodeService.class);
        CoreCodeCategoryService coreCodeCategoryService = ApplicationContextHelper.getBean(CoreCodeCategoryService.class);

        List<String> codeCategoryIdList = Arrays.stream(codeCategoryIds).collect(Collectors.toList());
        List<CoreCodeCategoryBean> categoryBeans = coreCodeCategoryService.selectListByIds(codeCategoryIdList);
        MapperParameter temp = new MapperParameter();
        temp.setFilter(SearchFilter.instance().match("codeCategoryId", codeCategoryIdList).filter(MatchPattern.OR));
        List<CoreCodeBean> coreCodeBeanList = coreCodeService.selectList(temp);
        Map<String, List<CoreCodeBean>> listMap = coreCodeBeanList.stream().collect(Collectors.groupingBy(CoreCodeBean::getCodeCategoryId));
        categoryBeans.forEach(c -> {
            if (coreCodeBeanList.stream().noneMatch(cc -> cc.getCodeCategoryId().equals(c.getId()))) {
                throw new InvalidDataException("【".concat(c.getCodeCategoryName()).concat("】未维护下拉选项内容！"));
            }
        });

        // 获取字段对应的下拉内容
        for (int i = 0; i < columns.length; i++) {
            String column = columns[i];
            String codeCategoryId = codeCategoryIds[i];
            if (listMap.containsKey(codeCategoryId)) {
                List<CoreCodeBean> coreCodeBeans = listMap.get(codeCategoryId);
                List<String> list = coreCodeBeans.stream().map(CoreCodeBean::getCodeName).distinct().collect(Collectors.toList());
                selectListMap.put(column, list);
            }
        }

        return selectListMap;
    }

    /**
     * 根据下拉内容填充下拉框（可以是非选择内容）
     *
     * @param sheet
     * @param rowIndex      标题行
     * @param selectListMap 填充的数据
     */
    public static void fillDropDown(Sheet sheet, int rowIndex, Map<String, List<String>> selectListMap) {
        int endRowNum = sheet.getPhysicalNumberOfRows();
        Row firstRow = sheet.getRow(rowIndex);
        int endCellNum = firstRow.getPhysicalNumberOfCells();
        //获取列信息：
        String[] columnNames = new String[endCellNum];
        for (int i = 0; i < endCellNum; i++) {
            Cell cell = firstRow.getCell(i);
            if (cell != null) {
                if (cell.getCellComment() != null) {
                    columnNames[i] = cell.getCellComment().getString().getString();
                } else {
                    columnNames[i] = "";
                }
            } else {
                columnNames[i] = "";
            }
        }
        //设置下拉框
        for (int i = 0; i < columnNames.length; i++) {
            String columnName = columnNames[i];
            if (selectListMap.containsKey(columnName)) {
                String[] strs = selectListMap.get(columnName).toArray(new String[0]);
                DataValidationHelper helper = sheet.getDataValidationHelper();
                DataValidationConstraint constraint = helper.createExplicitListConstraint(strs);
                //参数顺序：开始行、结束行、开始列、结束列
                CellRangeAddressList regions = new CellRangeAddressList(endRowNum, endRowNum + 998, i, i);
                DataValidation validation = helper.createValidation(constraint, regions);
                //适配xls和xlsx
                if (validation instanceof HSSFDataValidation) {
                    validation.setSuppressDropDownArrow(false);
                } else {
                    validation.setSuppressDropDownArrow(true);
                    validation.setShowErrorBox(true);
                }
                sheet.addValidationData(validation);
            }
        }
    }
}
